public class Example12_8 {
   public static void main(String args[ ]) {
      TicketHouse officer = new TicketHouse();
      Thread zhangfei,likui;
      zhangfei = new Thread(officer); 
      zhangfei.setName("�ŷ�");
      likui = new Thread(officer);  
      likui.setName("����");
      zhangfei.start();
      likui.start();
   }
}
class Bank implements Runnable {
   int money=200;
   public void setMoney(int n) {
      money=n;
   }
   public void run() {
      if(Thread.currentThread().getName().equals("���"))
         saveOrTake(300);
      else if(Thread.currentThread().getName().equals("����"))
         saveOrTake(150);;
   }
   public synchronized void saveOrTake(int amount) {
      if(Thread.currentThread().getName().equals("���")) {
         for(int i=1;i<=3;i++) {
            money=money+amount/3;
            System.out.println(Thread.currentThread().getName()+
                    "����"+amount/3+",������"+money+"��,��Ϣһ���ٴ�");
            try { Thread.sleep(1000);
            }
            catch(InterruptedException e){}
         }
      }
      else if(Thread.currentThread().getName().equals("����")) {
         for(int i=1;i<=3;i++) {
            money=money-amount/3;
            System.out.println(Thread.currentThread().getName()+
                    "ȡ��"+amount/3+"������"+money+"��,��Ϣһ����ȡ");
            try { Thread.sleep(1000);
            }
            catch(InterruptedException e){}
         }
      }
   }
}
class TicketHouse implements Runnable {
   int fiveAmount=2,tenAmount=0,twentyAmount=0;
   public void run() {
      if(Thread.currentThread().getName().equals("�ŷ�")) {
         saleTicket(20);
      }
      else if(Thread.currentThread().getName().equals("����")) {
         saleTicket(5);
      }
   }
   private synchronized void saleTicket(int money) {
      if(money==5) {
         fiveAmount=fiveAmount+1;
         System.out.println( "��"+Thread.currentThread().getName()+"�볡��,"+
                 Thread.currentThread().getName()+"��Ǯ����");
      }
      else if(money==20) {
         while(fiveAmount<3) {
            try { System.out.println("\n"+Thread.currentThread().getName()+"���ߵ�...");
               wait();
               System.out.println("\n"+Thread.currentThread().getName()+"������Ʊ");
            }
            catch(InterruptedException e){}
         }
         fiveAmount=fiveAmount-3;
         twentyAmount=twentyAmount+1;
         System.out.println("��"+Thread.currentThread().getName()+"�볡��,"+
                 Thread.currentThread().getName()+"��20������15Ԫ");
      }
      notifyAll();
   }
}



